# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 14:07:06 2013

@author: jkwong
"""
#PBAR_PlotZspecBasicHighZFinderHighMemoryWorkAround.py
#
#  Loads high-z markers, make diagnostic plots.
#  This script is basically the same as PBAR_PlotZspecBasicHighZFinder
# except that this is expected to be called from command line to deal with memory issues.
#
# 10/30/2013, JK, For testing the script, cy

import glob, os
import numpy as np
import PBAR_Zspec, PBAR_Cargo
import matplotlib.pyplot as plt
import copy
# image processing stuff
from skimage.filter import canny
from scipy import ndimage
from skimage import morphology

from skimage.filter import threshold_otsu
from skimage.segmentation import clear_border
from skimage.morphology import label, closing, square
from skimage.measure import regionprops
import objgraph
import sys


import gc

#from skimage.color import label2rgb
import PIL
from PIL import Image
import pickle
reload(PBAR_Zspec)

def RunThis(num):

    figureSize = (16, 10)
    
    # Global parameters
    
    newWidth = 600
    newHeight = 136
    xCargoInternalBounds = np.array((38, 550))
    yCargoInternalBounds = np.array((13, 106))
    cargoCountRange = np.array([0, 0.5e8]) # only consider parts of the zspec image that have rad below this value
    
    # make different size windows
    windowList = []
    windowList.append(np.array((2, 2)))
    windowList.append(np.array((4, 4)))
    #windowList.append(np.array((6, 6)))
    windowList.append(np.array((8, 8)))
    
    #discrimThresholdList = np.array((0, 2, 5, 7, 10, 12, 15, 17, 20))
    discrimThresholdList = np.array((7, 10, 15))
    
    #fractionPixelsList = np.array((0.7, 0.8, 0.9, 1.0))
    fractionPixelsList = np.array((0.8, 1.0))
    
    # energy centers
#    energy = np.array([7.50E+00,1.05E+01,1.35E+01,1.65E+01,1.95E+01,2.25E+01,2.55E+01, \
#        2.85E+01,3.15E+01,3.45E+01,3.75E+01,4.05E+01,4.35E+01,4.65E+01,4.95E+01,\
#        5.25E+01,5.55E+01,5.85E+01,6.15E+01,6.45E+01,6.75E+01,7.05E+01,7.35E+01, \
#        7.65E+01,7.95E+01,8.25E+01,8.55E+01,8.85E+01,9.15E+01,9.45E+01,9.75E+01,1.01E+02])
        
    # get linear discriminant coefficients, polynomial fits
    (wBest, pfitmean, pfitsigma) = PBAR_Zspec.GetZspecDiscrimValues()
    
    # explore making mask
    dataDir = r'C:\Users\jkwong\Documents\Work\PBAR\data3\BasicScansStandardWidth'
    plotDir = r'C:\Users\jkwong\Documents\Work\PBAR\data3\HighZFinderPlots'

    dataDir = r'E:\PBAR\data3b\BasicScansStandardWidth'
    plotDir = r'E:\PBAR\data3b\HighZFinderPlots'
    
    
    
    cargoConfigBaseDirList = glob.glob(os.path.join(dataDir, '*'))
    cargoConfigBaseDirList = cargoConfigBaseDirList[num:num+1]
    
    # round-about way of selecting the desired dataset 
    for (dirIndex, cargoConfigBaseDir) in enumerate(cargoConfigBaseDirList):
        subDirList = glob.glob(os.path.join(cargoConfigBaseDir, '*'))
        for (subDirIndex, dataPath) in enumerate(subDirList):
            gc.collect()
            print(dataPath)
            a, b = os.path.split(dataPath)
            a, c = os.path.split(a)
            
            plotSaveDir = os.path.join(plotDir, c, b)
            
            # make paths if not present
            if not os.path.exists(os.path.join(plotDir, c)):
                os.mkdir(os.path.join(plotDir, c))
    
            if not os.path.exists(plotSaveDir):
                os.mkdir(plotSaveDir)        
            
            temp = glob.glob(os.path.join(dataPath, '*cargoimage.npy'))
            fullFilenameCargo = temp[0]
            (a, filenameCargo) = os.path.split(fullFilenameCargo)
            
            # find the zspec scan number
            temp = glob.glob(os.path.join(dataPath, '*.npy'))
            # if file doesn't exist skip this set completely
            a, filename = os.path.split(temp[0])
            zspecScanNumber = filename[0:4]
            filenameZspec = filename
            fullFilenameZspec = os.path.join(dataPath, filename)
            
            # read in the markerfiles
            fullFilenameMarker = os.path.join(dataPath, fullFilenameCargo.replace('cargoimage.npy', 'cargomarker'))
    
            PBAR_Zspec.PlotZspecBasicHighZFinder(fullFilenameCargo, fullFilenameZspec, fullFilenameMarker, plotSaveDir, newWidth, newHeight, \
                xCargoInternalBounds, yCargoInternalBounds, cargoCountRange, windowList, \
                discrimThresholdList, fractionPixelsList, figureSize)
     
            objgraph.show_growth(limit=10)
    #       import pdb;pdb.set_trace()
    
            # try to free up memory
            gc.collect()


if __name__ == '__main__':
    RunThis(int(sys.argv[1]))
